<template>
	<view>
		<view class="container">
			<uni-steps :active="currentStep" :options="steps" style="padding: 20rpx;"></uni-steps>
		</view>
		<view v-show="currentStep === 0" >
			<view class="content">
				<uni-section title="基本信息" type="line">
					<view class="example">
						<!-- 基础用法，不包含校验规则 -->
						<uni-forms ref="form" :modelValue="baseFormData" labelWidth="100px">
							<uni-forms-item label="事项标题" name="sxbt">
								<uni-easyinput v-model="baseFormData.sxbt" placeholder="请输入事项标题" disabled />
							</uni-forms-item>
							<uni-forms-item label="事项性质" name="sxxz">
								<uni-data-select  v-model="baseFormData.sxxz" :localdata="sxxzDict" disabled
									@change="changeSxxzDict"></uni-data-select>
							</uni-forms-item>
              <uni-forms-item label="事项类型" name="sxlx" required>
                <uni-data-select v-model="baseFormData.sxlx" :localdata="sxlxDict" @change="changeSxlxDict"
                ></uni-data-select>
              </uni-forms-item>
							<uni-forms-item label="紧急程度" name="jjcd">
								<uni-data-checkbox v-model="baseFormData.jjcd" :localdata="jjcdDict" disabled
									@change="changeJjcdDict" />
							</uni-forms-item>
							<!-- <uni-forms-item label="间隔时间" name="jgsj" v-if="baseFormData.jjcd === '2'">
								<uni-data-select v-model="baseFormData.jgsj" :localdata="jgsjDict" disabled
									@change="changeJgsjDict"></uni-data-select>
							</uni-forms-item> -->
							<uni-forms-item label="是否反馈" name="sffk">
								<uni-data-checkbox v-model="baseFormData.sffk" :localdata="sffkDict" disabled
									@change="changeSffkDict" />
							</uni-forms-item>
							<uni-forms-item label="截止日期" name="jzrq" v-if="baseFormData.sffk === '1'">
								<uni-datetime-picker type="date" v-model="baseFormData.jzrq"  disabled/>
							</uni-forms-item>
						</uni-forms>

						<el-row>
							<el-col :span="6">
								<label>相关文件：</label>
							</el-col>
							<el-col :span="18">
								<el-upload class="upload-demo" :action="uploadParam.uploadUrl"
									:headers="uploadParam.headers" :before-upload="rwBeforeUpload" :on-change="handleChange"
									:on-error="handleUploadError" :on-success="handleUploadSuccess" :auto-upload="true"
									:on-remove="removeFile" ref="upload" multiple :file-list="uploadParam.showFileList">
								</el-upload>
							</el-col>
						</el-row>
            <el-row>
              <el-col :span="6">
                <label>下达内容：</label>
              </el-col>
              <el-col>
                <uni-easyinput autoHeight disabled  type="textarea"  v-model="baseFormData.xdnr"/>
              </el-col>
            </el-row>

						<el-row v-for="option in parentOptions">
							<el-col :span="6">
								<label>{{option.level+'意见'}}</label>
							</el-col>
							<el-col>
								<uni-easyinput autoHeight type="textarea" disabled v-model="option.spyj"/>
							</el-col>
						</el-row>
            <el-row>
              <el-col :span="6">
                <label>{{option.level+'审批意见'}}：</label>
              </el-col>
              <el-col>
                <uni-easyinput  v-show="option.spStatus==1"  autoHeight disabled  type="textarea"  v-model="spyj"/>
                <uni-easyinput  v-show="option.spStatus==0"  autoHeight  type="textarea"  v-model="spyj"/>
              </el-col>
            </el-row>
          </view>
          <div v-if="baseFormData.sffk==1" class="box" style="border: none">
            <el-row>
              <label>反馈内容：</label>
              <el-upload class="upload-demo" :action="fkUploadParam.uploadUrl" :headers="fkUploadParam.headers"
                         :before-upload="rwBeforeUpload" :on-change="fkHandleChange" :on-error="handleUploadError"
                         :on-success="handleUploadSuccess" :auto-upload="false" ref="fkUpload" multiple
                         :file-list="fkUploadParam.fileList"
                         :on-remove="fkRemoveFile"
              >
                <el-button :disabled="option.fkzt == 3" slot="trigger" type="primary" icon="el-icon-upload" size="small">上传</el-button>
              </el-upload>
            </el-row>
            <div>
              <uni-easyinput  :disabled="option.fkzt == 3"  autoHeight  type="textarea"  v-model="fknr"/>
            </div>
          </div>
          <view class="action-btn">
<!--            <button :disabled="sfsp" style="margin-bottom: 10px"  @click="submitFrom" class="bg-blue lg round">转达下级</button>-->
            <button :disabled="option.fkzt == 3" v-loading.fullscreen.lock="submitFkLoading" style="margin-bottom: 10px" @click="submitAppZjxdFk()" class="bg-blue lg round">提交反馈</button>
            <button :disabled="sfsp" style="margin-bottom: 10px" @click="goToNextStep" class="bg-blue lg round">下达基层</button>
          </view>
				</uni-section>
			</view>
		</view>

		<view v-show="currentStep === 1">
			<view class="container">
				<view class="uni-padding-wrap uni-common-mt">
					<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" />
				</view>
				<view class="content" style="overflow-y: scroll;height: 500px">
					<view v-if="current === 0">
						<el-tree ref="tree" node-key="id" :data="deptTree" :default-expanded-keys="checkTreeIds"
							:default-checked-keys="checkTreeIds" show-checkbox :props="defaultProps"
							@check="check"></el-tree>
					</view>
					<view v-if="current === 1">
						<view class="article">
							<el-checkbox-group v-model="checkList">
								<el-checkbox class="tabClass" v-for="tab in tabList" :label="tab.id"
									:key="tab.id">{{ tab.name }}
								</el-checkbox>
							</el-checkbox-group>
						</view>
					</view>
				</view>

				<view class="action-btn fixed-bottom">
					<view class="two_button">
						<button @click="goToBackStep" type="default" plain="true" class="round"
							style="width: 45%;">上一步</button>
						<!-- <button @click="submit()" class="bg-blue lg round" style="width: 45%;">提交</button> -->
						<el-button v-loading.fullscreen.lock="submitLoading" @click="submit()" type="primary" round
							style="width: 45%;">下达任务</el-button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getDicts
	} from "@/api/system/dict/data";
	import { getTxlDeptByid, getTxlTab ,getDepartmentList,getUserLabelList} from "@/api/system/xdwj";
  import {
    getAppZjxdRwbInfo,
    getAppCityLevel,
    tranAppXdrwToUser, submitAppZjxdFk
  } from "@/api/system/yjgl";
	import config from '@/config';
  import {
    getDeptId,
    getToken,
    getUsername
  } from '@/utils/auth'


	export default {
		data() {
			return {
        submitFkLoading: false,
        submitLoading: false,
				currentStep: 0, // 当前步骤，初始为0
				steps: [ // 步骤列表
					{
						title: '维护信息'
					},
					{
						title: '选择部门/标签'
					}
				],
				// 基础表单数据
				spyj: "",
        sfsp: false,
        parentOptions: [],
				workid: "",
				parentSpyj: "",
				baseFormData: {
					sid: "",
					sxbt: "",
					sxxz: "",
					jjcd: "",
					jgsj: "",
					sffk: "",
					jzrq: ""
				},
        fkUploadParam: {
          // 上传的图片服务器地址
          uploadUrl: config.baseUrl + "/common/upload",
          headers: {
            Authorization: "Bearer " + getToken()
          },
          fileType: [
            ["doc", "xls", "ppt", "txt", "pdf"],
          ],
          fileList: [],
          showFileList: []
        },
				sxxzDict: [],
        sxlxDict: [],
				sffkDict: [],
				option: [],
				fknr: [],
				jjcdDict: [],
				jgsjDict: [{
						value: "0.5",
						text: "半小时"
					},
					{
						value: "1",
						text: "1小时"
					},
					{
						value: "2",
						text: "2小时"
					},
					{
						value: "3",
						text: "3小时"
					},
					{
						value: "5",
						text: "5小时"
					},
					{
						value: "8",
						text: "8小时"
					},
					{
						value: "12",
						text: "12小时"
					},
					{
						value: "24",
						text: "24小时"
					},
					{
						value: "48",
						text: "48小时"
					}
				],

				current: 0,
				items: ['部门', '标签'],
				checkList: [], //选中的tab
				tabList: [],
				checkTreeIds: [], //选中的部门ID
				deptTree: [],
				defaultProps: {
					children: 'children',
					label: 'name'
				},

				uploadParam: {
					// 上传的图片服务器地址
					uploadUrl: config.baseUrl + "/common/upload",
					headers: {
						Authorization: "Bearer " + getToken()
					},
					fileType: [
						["doc", "xls", "ppt", "txt", "pdf"],
					],
					fileList: [],
					showFileList: []
				},
			}
		},
		onLoad(options) {
			this.baseFormData.sid = options.sid;
		},
		created() {
			this.workid = new Date().getTime() + Math.random().toString(36).substr(2);
			// 字典翻译
			getDicts("sxxz").then(response => {
				for (let item of response.data) {
					this.sxxzDict.push({
						"text": item.dictLabel,
						"value": item.dictValue
					})
				}
			});
      getDicts("sxlx").then(response => {
        for (let item of response.data) {
          this.sxlxDict.push({"text": item.dictLabel, "value": item.dictValue})
        }
      });
			getDicts("sffk").then(response => {
				for (let item of response.data) {
					this.sffkDict.push({
						"text": item.dictLabel,
						"value": item.dictValue
					})
				}
			});
			getDicts("jjcd").then(response => {
				for (let item of response.data) {
					this.jjcdDict.push({
						"text": item.dictLabel,
						"value": item.dictValue
					})
				}
			});
			getDepartmentList({deptId:getDeptId()}).then(res => {
				this.deptTree = res.data;
			});
			getUserLabelList({}).then(res => {
			  this.tabList = res.data;
			});
			this.getAppCityLevel();
			this.getInfo();
		},
		methods: {
      submitAppZjxdFk() {
        this.submitFkLoading = true;
        this.$refs.fkUpload.submit();
        let data = {
          "fjbs": this.fkUploadParam.fileList,
          "sid": this.option.id,
          "fknr":this.fknr
        }
        this.submitFkLoading = false;
        console.log(data);
        setTimeout(res => {
          submitAppZjxdFk(data).then(res => {
            if (res.code == 200) {
              this.submitFkLoading = false;
              uni.switchTab({
                url: '/pages/index',
              })
            } else {
              this.$modal.msgError(res.msg);
            }
          })
        }, 2000)
      },
      fkRemoveFile(file, fileList) {
        this.fkUploadParam.fileList = fileList;
      },
      fkHandleChange(file, fileList) {
        this.fkUploadParam.fileList = fileList;
      },
			getInfo(){
				getAppZjxdRwbInfo({sid: this.baseFormData.sid, username: getUsername() }).then(res => {
          if (res.data.parentOptions.length>0){
            this.parentSpyj = res.data.parentOptions[0].spyj;
          }
          this.sfsp = res.data.sfsp;
          this.option = res.data.option;
          if (this.option){
            this.fknr = this.option.fknr;
          }
          this.spyj = res.data.option.spyj;
          this.checkedCities = res.data.deptIds;
          this.parentOptions = res.data.parentOptions;
          // this.baseFormData.sid = res.data.sid;
					// this.baseFormData.sxbt = res.data.sxbt;
					// this.baseFormData.sxxz = res.data.sxxz;
					// this.baseFormData.jjcd = res.data.jjcd;
					// this.baseFormData.sffk = res.data.sffk;
					// this.baseFormData.jzrq = res.data.jzrq;
					// this.baseFormData.sxbt = res.data.sxbt;
          this.baseFormData = res.data;
					this.uploadParam.fileList = res.data.fjbs;
					res.data.fjbs.forEach(item =>{
						this.uploadParam.showFileList.push({
							url : item.wjdz,
							name : item.wjmc
						})
					});
					console.log(this.uploadParam.fileList)
				});
			},
			getAppCityLevel(){
			  getAppCityLevel({username:  getUsername()}).then(res=>{
				if (res.code==200){
				  this.cityOptions = res.data;
				  this.cities = this.cityOptions;
				}
			  })
			},
			handleCheckAllChange(val) {
			  this.checkedCities = val ? this.cityOptions.map(m=>m.deptId) : [];
			  this.isIndeterminate = false;
			},
			handleCheckedCitiesChange(value) {
			  let checkedCount = value.length;
			  this.checkAll = checkedCount === this.cities.length;
			  this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
			},
			goToBackStep() {
				this.currentStep--;
			},
			goToNextStep() {
				if (this.currentStep === 0) {
					console.log(this.baseFormData)
					this.currentStep++; // 增加当前步骤索引
				}
			},
			changeSxxzDict(e) {
				this.baseFormData.sxxz = e
			},
      changeSxlxDict(e) {
				this.baseFormData.sxlx = e
			},
			changeJjcdDict(e) {
				this.baseFormData.jjcd = e.detail.value
			},
			changeJgsjDict(e) {
				this.baseFormData.jgsj = e
			},
			changeSffkDict(e) {
				this.baseFormData.sffk = e.detail.value
			},
			submitUpload() {
				this.$refs.upload.submit();
			},
			// 上传失败
			handleUploadError(err) {
				console.log("上传失败...")
				this.$modal.msgError("上传文件失败，请重试");
				this.$modal.closeLoading();
			},
			rwBeforeUpload(file) {
				console.log("上传前...");
			},
			handleChange(file, fileList) {
				this.uploadParam.fileList = fileList;
			},
			// 上传成功回调
			handleUploadSuccess(res, file) {
				console.log("上传成功...");
			},
			// 移除附件操作
			removeFile(file, fileList) {
				this.uploadParam.fileList = fileList;
			},
			onClickItem(e) {
				if (this.current != e.currentIndex) {
					this.current = e.currentIndex;
				}
			},
			check() {
				let selectDepts = this.$refs.tree.getCheckedNodes();
				let deptIds = selectDepts.map(d => d.id);
				deptIds = selectDepts.filter(dept => !deptIds.includes(dept.parentId));
				this.checkTreeIds = deptIds.map(d => d.id)
			},
			submit() {
				this.submitLoading = true
				this.baseFormData.rwlx = "2";
				const checkTabIds = this.checkList.map(String);
				const data = {
					'username': getUsername(),
					'zjxdRwb': this.baseFormData,
					'fjbs': this.uploadParam.fileList,
					'deptIds': this.checkTreeIds,
					'tabIds': checkTabIds,
					'ly': '2',
					'spyj': this.spyj,
					"workid": this.workid
				}
				console.log(data)
				tranAppXdrwToUser(data).then(res => {
					this.submitLoading = false;
					this.$modal.msgSuccess("添加成功");
					uni.navigateBack()
				}).catch(err => {
					console.log('err', err);
					this.$modal.msgError("添加失败");
					this.submitLoading = false;
				});
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f5f6f7;
	}

	.container {
		background-color: white;
		margin: 20rpx;
		border-radius: 20rpx;
	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.fixed-bottom {
		position: fixed;
		bottom: var(--window-bottom);
		bottom: 0;
		width: 95%;
		margin-bottom: 20rpx;
		z-index: 999;
	}

	.two_button {
		display: flex;
	}

	.article {
		background-color: white;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
	}

	.tabClass {
		font-size: 80rpx;
		margin-left: 40rpx;
		margin-right: 400rpx;
	}

	::v-deep .is-disabled {
		color: black !important;
	}

</style>
